<?php
declare(strict_types=1);

namespace App\Utils\Other\Sandpay;

use App\Exception\InternalException;
use App\Utils\Http\Request;
use Hyperf\Collection\Arr;
use function Hyperf\Config\config;
use function Hyperf\Support\make;

Class App {

    /**
     * 产品ID 00002021-微信小程序00002020-微信公众号
     * @var string
     */
    protected string $productId;

    /**
     * 回调地址
     * @var string
     */
    protected string $notify;

    /**
     * 微信APPID
     * @var string
     */
    protected string $appid;

    /**
     * 路径
     * @var string
     */
    protected string $path;

    /**
     * 配置
     * @var array
     */
    protected array $config;

    public function __construct()
    {
        $this->config = config('cloud.sandpay');
    }

    /**
     * 参数拼接
     * @param array $params
     * @return array
     */
    protected function getParams(array $params)
    {
        $append = [
            'productId' => $this->productId,
            'appid' => $this->appid,
            'notify' => $this->notify,
            'merchant' => 'SX'
        ];

        return array_merge($params, $append);
    }

    /**
     * 请求
     * @param array $params
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function request(array $params=[]):array
    {
        /** @var Request $http */
        $http = make(Request::class);
        $response = json_decode($http->post($this->config['domain'].$this->path, $params), true);
        logs(json_encode($response, JSON_UNESCAPED_UNICODE));

        return $this->response($response, $params);
    }

    /**
     * 响应
     * @param $response
     * @param array $params
     * @return array
     */
    protected function response($response, array $params=[]):array
    {
        if (!isset($response['code']) || $response['code'] != 0) {
            $message = Arr::get($response, 'message');
            if (!$message) {
                throw new InternalException('response is null');
            }
            $messageJson = json_decode($message, true);
            if (false === $messageJson || !Arr::has($messageJson, 'head') || !Arr::has($messageJson['head'], 'respMsg')) {
                throw new InternalException($message);
            }
            throw new InternalException($messageJson['head']['respMsg']);
        }

        if (is_string($response['data'])) {
            $data = json_decode($response['data'], true);
            $body = Arr::get($data, 'params', []);
        } else {
            $body = Arr::get($response['data']['body']);
        }

        return [
            $params,
            $response,
            $body
        ];
    }
}